package org.ecype.diego;

import java.util.HashMap;
import java.util.Map;

import androidx.persistence.ColumnType;

public class EntityToSqlConverter {

	private static final Map<ColumnType, String> typesMap;

	static {
		typesMap = new HashMap<ColumnType, String>(7);
		typesMap.put(ColumnType.INT, "INTEGER");
		typesMap.put(ColumnType.LONG, "INTEGER");
		typesMap.put(ColumnType.SHORT, "INTEGER");
		typesMap.put(ColumnType.FLOAT, "REAL");
		typesMap.put(ColumnType.DOUBLE, "REAL");
		typesMap.put(ColumnType.STRING, "TEXT");
		typesMap.put(ColumnType.BLOB, "BLOB");
	}

	public String getCreateTableSql(Entity entry) {
		StringBuilder sql = new StringBuilder();
		sql.setLength(0);

		sql.append("CREATE TABLE IF NOT EXISTS ").append(entry.getName()).append(" (\n");

		boolean first = true;
		for (Column column : entry) {
			if (first) {
				first = false;
			} else {
				sql.append(",\n");
			}

			sql.append("\t");
			sql.append(column.getName()).append(' ');
			sql.append(typesMap.get(column.getType()));

			if (column.isId()) {
				sql.append(" PRIMARY KEY");
				if (column.isAutoincrement()) {
					sql.append(" AUTOINCREMENT");
				}
			}

			if (!column.isNullable()) {
				sql.append(" NOT NULL");
			}

			if (column.isUnique()) {
				sql.append(" UNIQUE");
			}

			if (column.hasDefaulfValue()) {
				sql.append(" DEFAULT ").append(column.getDefaulfValue());
			}

			if (column.isReference()) {
				Reference reference = column.getReference();
				Entity parent = reference.getParent();
				sql.append("\n\t\tREFERENCES ").append(parent.getName());
				sql.append("(").append(reference.getParentColumn()).append(")");
				// sql.append("\n\t\tON DELETE NO ACTION");
				// sql.append("\n\t\tON UPDATE NO ACTION");
			}
		}
		sql.append("\n);");
		return sql.toString();
	}

}
